package com.zx.cloud.file;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

//@Component
public class FileServerUtils {
	@Value("${file.dir}")
	private String dir;
	
	private String localDir = "/tmp/images/";
	
	/**
	 * 1.判断文件是否为图片 jpg|png|gif 2.防止恶意程序 高度和宽度判断 3.图片分文件保存 分布式fast|yyyy/MM/dd
	 * 4.修改文件名称，防止重名 UUID
	 */
	public String imageFileUpload(MultipartFile uploadFile) {
		// 1.判断文件是否为图片类型
		String fileName = uploadFile.getOriginalFilename();
		fileName = fileName.toLowerCase(); // 解决文件名后缀是大写的
		if (!fileName.matches("^.+\\.(jpg|png|gif)$")) {
			// 表示不满足规则
			return "";
		}
		// 2.判断是否为恶意程序,转化成为图片对象
		try {
			BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
			int width = bufferedImage.getWidth();
			int height = bufferedImage.getHeight();
			if (width == 0 || height == 0) {
				return "恶意文件";
			}

			// 3.实现份文件存储 按照yyyy/MM/dd
//			String dateDir = "";// new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
			String fileDirPath = this.getLocalDir();// localDir + dateDir;
			File dirFile = new File(fileDirPath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			// 4.生成文件防止重名 name.type
			int index = fileName.lastIndexOf(".");
			String fileType = fileName.substring(index);
			String uuid = UUID.randomUUID().toString();
			// 拼接文件名称
			fileName = uuid + fileType;
			// 5.文件实现上传
			uploadFile.transferTo(new File(fileDirPath + fileName));
		} catch (IOException e) {
			e.printStackTrace();
			return "文件存储失败";
		}
		return fileName;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public String getLocalDir() {
		if (StringUtils.isNotBlank(dir)) {
			StringBuffer sbn = new StringBuffer();
			sbn.append(dir).append(":").append(localDir);
			return sbn.toString();
		}
		return localDir;
	}

	public void setLocalDir(String localDir) {
		this.localDir = localDir;
	}
}
